import requests
import json
import hashlib
import time


# def call_api(endpoint, method='POST', payload=None, appid=None):
#     """
#     调用API接口（带签名认证）
#
#     参数:
#         endpoint: API地址
#         method: 请求方法 (GET/POST)
#         payload: 请求参数 (字典)
#         appid: 应用ID (需替换为实际值)
#     """
#     # 准备请求参数
#     payload = payload or {}
#     payload_json = json.dumps(payload, separators=(',', ':'))
#
#     # 生成时间戳（毫秒级）
#     timestamp = str(int(time.time() * 1000))
#
#     ak = "09(o5PCgrswUU6BpJpfwukFZXiE@JKe2f"
#
#     # 生成签名（核心部分）
#     sign_str = timestamp + payload_json + appid + ak
#     x_sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
#
#     # 构造请求头
#     headers = {
#         'x-ca-timestamp': timestamp,
#         'x-ca-appid': appid,
#         'x-sign': x_sign,
#         'Content-Type': 'application/json',
#         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
#     }
#
#     # 打印调试信息（可选）
#     print("=" * 50)
#     print(f"请求地址: {endpoint}")
#     print(f"请求方法: {method}")
#     print(f"请求参数: {payload_json}")
#     print(f"时间戳: {timestamp}")
#     print(f"签名字符串: {sign_str}")
#     print(f"生成签名: {x_sign}")
#
#     try:
#         # 发送请求
#         if method.upper() == 'GET':
#             response = requests.get(endpoint, headers=headers, params=payload)
#         else:
#             response = requests.post(endpoint, headers=headers, data=payload_json)
#
#         # 返回响应
#         return response
#
#     except requests.exceptions.RequestException as e:
#         return {"error": f"请求失败: {str(e)}"}
#
#
# # 示例使用
# if __name__ == "__main__":
#     # 配置参数（需替换为实际值）
#     API_URL = "https://adm-test.deepaym.com/admin/merchantStatistics/supportPayinMethod"
#     APP_ID = "YOUR_REAL_APPID"  # 替换为实际AppID
#     PAYLOAD = {"mid": "10001"}  # 替换为实际请求参数
#
#     # 调用API
#     response = call_api(
#         endpoint=API_URL,
#         method="POST",
#         payload=PAYLOAD,
#         appid=APP_ID
#     )
#
#     # 处理响应
#     print("\n" + "=" * 50)
#     print("响应状态码:", response.status_code)
#     print("响应头:", json.dumps(dict(response.headers), indent=2))
#
#     try:
#         print("响应内容:", json.dumps(response.json(), indent=2))
#     except:
#         print("响应文本:", response.text)




def get_payment_inquiry_pdf(data, order_id):
    # 代付的接口
    url = data['address'] + "/admin/payoutOrder/openInfo"
    print("url",url)

    # 1. 准备请求数据
    payload = {"mid": data['mid'], "downstream_sn": order_id}
    payload_json = json.dumps(payload, separators=(',', ':'))  # 紧凑JSON格式

    # 2. 获取当前时间戳（毫秒级）
    timestamp = str(int(time.time() * 1000))  # 13位毫秒级时间戳
    # 或使用秒级：timestamp = str(int(time.time()))  # 10位秒级

    # 3. 设置AppID（需使用实际值，非任意值）
    appid = "123456"  # 替换为真实AppID
    ak = "09(o5PCgrswUU6BpJpfwukFZXiE@JKe2f"
    # 4. 生成签名（关键步骤）
    # 格式: md5(timestamp + payload + appid)
    sign_str = timestamp + payload_json + appid + ak
    x_sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest()

    # 5. 构造请求头
    headers = {
        'x-ca-timestamp': timestamp,
        'x-ca-appid': appid,
        'x-sign': x_sign,
        'Content-Type': 'application/json'
    }

    # 6. 发送请求
    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload_json  # 使用data而不是json
        )

        # 输出详细响应信息
        print(f"状态码: {response.status_code}")
        print("响应头:")
        for k, v in response.headers.items():
            print(f"  {k}: {v}")

        print("\n响应内容:")
        try:
            return json.dumps(response.json(), indent=2)
            print(json.dumps(response.json(), indent=2))
        except:
            print(response.text)

    except requests.exceptions.RequestException as e:
        print(f"请求失败: {str(e)}")

if __name__ == '__main__':

    data={'address': 'https://adm.deepay.ink', 'mid': '12271'}
    order_id="EPAYG1bad31ac8491947f68cOut"

    d=get_payment_inquiry_pdf(data, order_id)

    print(d)